
import Taro, {Component} from '@tarojs/taro'
import {View, Image, Text} from '@tarojs/components'
import html2canvas from "html2canvas"
import { QRCode } from 'taro-code'

import {companyName, getAvatar, getUserInfo, navigateTo, userType} from "../../utils/common";


import './index.scss'

class ShareIndex extends Component {

  state = {
    userInfo: {} ,
    shareImgSrc: '',
    isShow: false,
    serverHost: window.location.origin
  }

  componentWillMount(): void {
    let userInfo = getUserInfo()
    this.setState({
      userInfo
    })
  }

  componentDidMount(): void {
    this.getJsApiParam()
  }

  componentDidShow(): void {
    this.share()
  }

  link(url: string = '/pages/index/index'): void {
    navigateTo(url)
  }

  close(e) {
    e.preventDefault()
    e.stopPropagation()
    this.setState({ isShow: false })
  }

  html2Canvas = () => {
    let shareContent = document.getElementById('share-canvas');//需要截图的包裹的（原生的）DOM 对象
    let width = shareContent.offsetWidth; //获取dom 宽度
    let height = shareContent.offsetHeight; //获取dom 高度

    let opts = {
      scale: 2, // 添加的scale 参数
      logging: true, //日志开关
      width: width, //dom 原始宽度
      height: height, //dom 原始高度
      backgroundColor: 'transparent',
      useCORS: true,
      allowTaint: true,
      logging: false,
    };
    const that = this;
    Taro.showLoading({ title: '海报生成中...' })
    html2canvas(shareContent, opts).then( canvas => {
      Taro.hideLoading()
      this.setState({ isShow: true })
      let shareImgSrc = canvas.toDataURL("image/jpeg")
      that.setState({ shareImgSrc: shareImgSrc })
    })
  }

  // 配置微信分享
  getJsApiParam = () => {
    let currentUrl = window.location.href
    let apiUrl = `${this.state.serverHost}/Wechat/getWxJsApiParams?curUrl=${currentUrl}`
    Taro.showLoading({title: '加载中...'})
    fetch(apiUrl, {
      method: "GET",
      mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin'
    })
      .then(response => {
        Taro.hideLoading()
        return response.json()
      })
      .then(response => {
        let appId = response.appId
        let timestamp = response.timestamp
        let nonceStr = response.nonceStr
        let signature = response.signature
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature,// 必填，签名
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      })
      .catch(error => {
        console.log(error)
      })
  }

  share() {
    let { userInfo } = this.state
    let url = `${this.state.serverHost}/v4/#/pages/index/index?sourceUserId=${userInfo.id}`
    let title = `${companyName}-生态农业旅游平台!`
    let desc = '一起来养鱼'
    let imgUrl = `${this.state.serverHost}/v4/static/logo.jpg`
    var shareData = {
      title,
      desc,
      imgUrl,
      url,
      link: url
    };
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
  }

  render() {
    let { userInfo,shareImgSrc,isShow,serverHost } = this.state
    return (
      <View className='share-wrap'>
        <View className='share-canvas' id='share-canvas' onClick={this.html2Canvas.bind(this)}>
          <Image className='share-bg' src={require('../../assets/img/share_02.png')} />
          <View className='share-con'>
            {/* <Image className='share-ad' src={require('../../assets/img/img_04.png')}/>*/}
            <View className='share-info'>
              <Image className='share-header' src={getAvatar(userInfo.avatar)} />
              <View className='share-username'>{userInfo.nickName} {/* <Text className='viple' >{userInfo.graName || '游客' }</Text> */} </View>
              <View className='share-code'>
                <QRCode
                  text={serverHost+'/v4/#/pages/index/index?sourceUserId='+userInfo.id || ''}
                  size={130}
                  scale={4}
                  errorCorrectLevel='M'
                  typeNumber={2}
                />
              </View>
              <View className='share-tip'>微信扫一扫 轻松来养鱼</View>
            </View>
          </View>
        </View>

        {isShow&&
        <View className='share-img' onClick={this.close.bind(this)}>
           <Image className='img img-active' src={shareImgSrc} />
           <View className='tipsText'>长按保存图片、识别二维码</View>
        </View>
        }
      </View>
    )
  }
}

export default ShareIndex
